package com.sinosoft.hydra.um.services.aop;

import cn.com.sinux.spring.exception.BusinessException;
import com.sinosoft.hydra.logging.LogModules;
import com.sinosoft.hydra.um.helper.AuthContextHelper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2015/8/28.
 */
@Component
@Aspect
public class ServiceAOP {

    @Pointcut("execution(* com.sinosoft.hydra.um.services.*.*(..))")
    public void aspect() {
    }

    @AfterThrowing(value = "aspect()", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Exception ex) throws Exception {
        if(ex instanceof BusinessException){
            BusinessException bs = (BusinessException) ex;
            throw bs;
        }
        Object[] args = joinPoint.getArgs();
        StringBuilder stringBuilder = new StringBuilder(joinPoint.getSignature().toString());
        if (ex instanceof NullPointerException) {
            stringBuilder.append("异常原因：业务传参不正确");
        } else {
            stringBuilder.append("异常原因：").append(ex.getMessage());
        }
        if (args != null && args.length > 0) {
            stringBuilder.append("，参数(");
            for (Object arg : args) {
                stringBuilder.append(arg == null ? "NULL" : arg).append("，");
            }
            stringBuilder.append(")");
        }
        LoggerFactory.getLogger(LogModules.STD_APPENDER).error("{}", stringBuilder.toString());
//        throw new BusinessException("system.server.error");
        throw ex;
    }

    @Before(value = "aspect()")
    public void beforeRun() {
        AuthContextHelper.setTime(System.currentTimeMillis());
    }

    @After(value = "aspect()")
    public void afterRun(JoinPoint joinPoint) {
        long times = AuthContextHelper.getTime();
        if (times != -1) {
            StringBuilder stringBuilder = new StringBuilder("执行").append(joinPoint.getSignature().toString());
            stringBuilder.append("结束,共耗费时间").append(System.currentTimeMillis() - times).append("ms");
            LoggerFactory.getLogger(LogModules.STD_LOGGER).debug("{}", stringBuilder.toString());
        }
    }
}
